{% extends 'user/base.html' %}

{% block content %}
    <main class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8" style="margin-top:-40px">
        <!-- 搜索与排序 -->
        <form method="get" action="{{ url_for('user.index') }}" class="mb-6 flex flex-wrap items-end gap-4">
            <div class="flex-1 min-w-[200px] relative">
                <label for="search" class="block text-sm font-medium text-gray-700 mb-1">搜索影片</label>
                <input type="text" id="search" name="search" value="{{ search }}"
                       placeholder="请输入电影名"
                       class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring focus:border-blue-300 shadow-sm pr-10"
                />
                <button type="button" id="clear-input"
                        class="absolute right-3 top-[36px] text-gray-400 hover:text-gray-600 text-lg leading-none"
                        title="清除">
                    ✕
                </button>
            </div>

            <div class="min-w-[240px]">
                <label for="sort" class="block text-sm font-medium text-gray-700 mb-1">排序方式</label>
                <select name="sort" id="sort"
                        class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-white focus:outline-none focus:ring focus:border-blue-300 shadow-sm">
                    <option value="rate_desc" {% if sort == 'rate_desc' %}selected{% endif %}>
                        评分从高到低
                    </option>
                    <option value="rate_asc" {% if sort == 'rate_asc' %}selected{% endif %}>
                        评分从低到高
                    </option>
                    <option value="year_desc" {% if sort == 'year_desc' %}selected{% endif %}>
                        上映时间从新到旧
                    </option>
                    <option value="year_asc" {% if sort == 'year_asc' %}selected{% endif %}>
                        上映时间从旧到新
                    </option>
                </select>
            </div>

            <div>
                <button type="submit"
                        id="searchBtn"
                        class="inline-block min-w-[80px] bg-blue-600 text-white px-5 py-2 rounded-lg hover:bg-blue-700 transition">
                    搜索
                </button>
                <button id="clear-search" type="button"
                        class="inline-block min-w-[80px] bg-blue-600 text-white px-5 py-2 rounded-lg hover:bg-blue-700 transition">
                    重置
                </button>
            </div>
        </form>
        <div class="flex">
            <div class="flex-1 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- Movie Card -->
                {% for movie in pagination.current_items %}
                    <a href="{{ url_for('user.movie_detail', movie_id=movie.id) }}"
                       class="block hover:shadow-xl transition-shadow duration-200">
                        <div class="movie-card bg-white rounded shadow-lg overflow-hidden">
                            <div class="relative pb-[150%]">
                                <img src="{{ url_for('static', filename=movie.image_link) }}"
                                     class="absolute inset-0 w-full h-full object-cover">
                            </div>
                            <div class="p-4">
                                <h3 class="text-lg font-semibold mb-2 truncate"
                                    title="{{ movie.name }}">{{ movie.name }}</h3>
                                <div class="flex items-center mb-2">
                                    <div class="rating-stars mr-2">
                                        {% set score = movie.rate %}
                                        {% set star_count = score / 2 %}
                                        {% set full_stars = star_count | int %}
                                        {% set half_star = 1 if star_count - full_stars >= 0.5 else 0 %}
                                        {% set empty_stars = 5 - full_stars - half_star %}

                                        {# 实心星星 #}
                                        {% for i in range(full_stars) %}
                                            <i class="fas fa-star"></i>
                                        {% endfor %}

                                        {# 半星 #}
                                        {% if half_star %}
                                            <i class="fas fa-star-half-alt"></i>
                                        {% endif %}

                                        {# 空心星星 #}
                                        {% for i in range(empty_stars) %}
                                            <i class="far fa-star"></i>
                                        {% endfor %}
                                    </div>
                                    <span class="text-sm text-gray-600">{{ movie.rate | round(1) }}</span>
                                </div>
                                <p class="text-sm text-gray-500">{{ movie.years }} 上映</p>
                            </div>
                        </div>
                    </a>
                {% endfor %}
            </div>

            <!-- Recommendations Section -->
            <div class="ml-8 w-80" id="recommend-container">
                <div class="bg-white rounded-lg shadow-lg p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h2 class="text-xl font-semibold">推荐观看</h2>
                        <button id="refresh-btn" class="text-sm text-blue-600 hover:underline focus:outline-none">
                            换一批
                        </button>
                    </div>
                    <!-- Recommended Movie -->
                    {% for movie in recommend %}
                        <a href="{{ url_for('user.movie_detail', movie_id=movie.id) }}"
                           class="block hover:shadow-xl transition-shadow duration-200">
                            <div class="flex mb-4 pb-4 border-b border-gray-100">
                                <div class="w-20 h-28 flex-shrink-0">
                                    <img src="{{ url_for('static', filename=movie.image_link) }}"
                                         class="w-full h-full object-cover rounded">
                                </div>
                                <div class="ml-4">
                                    <h3 class="font-semibold mb-1 truncate max-w-[160px]"
                                        title="{{ movie.name }}">{{ movie.name }}</h3>
                                    <div class="rating-stars text-sm mb-1">
                                        {% set score = movie.rate %}
                                        {% set star_count = score / 2 %}
                                        {% set full_stars = star_count | int %}
                                        {% set half_star = 1 if star_count - full_stars >= 0.5 else 0 %}
                                        {% set empty_stars = 5 - full_stars - half_star %}

                                        {# 实心星星 #}
                                        {% for i in range(full_stars) %}
                                            <i class="fas fa-star"></i>
                                        {% endfor %}

                                        {# 半星 #}
                                        {% if half_star %}
                                            <i class="fas fa-star-half-alt"></i>
                                        {% endif %}

                                        {# 空心星星 #}
                                        {% for i in range(empty_stars) %}
                                            <i class="far fa-star"></i>
                                        {% endfor %}
                                    </div>
                                    <p class="text-sm text-gray-500">{{ movie.rate }} 分</p>
                                </div>
                            </div>
                        </a>
                    {% endfor %}
                </div>
            </div>
        </div>

        <div style="margin-top: 20px;">
            {% with endpoint='user.index', url_params={} %}
                {% include 'user/components/page.html' with context %}
            {% endwith %}
        </div>
    </main>
{% endblock %}

{% block scripts %}
    {{ super() }}
    <script>
        document.addEventListener('click', async function (e) {
            if (e.target && e.target.id === 'refresh-btn') {
                const btn = e.target;
                btn.disabled = true;
                btn.innerText = '加载中...';

                try {
                    const res = await fetch('{{ url_for("user.refresh_recommend") }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({refresh: true})
                    });

                    if (!res.ok) throw new Error('请求失败');

                    const data = await res.json();

                    // 替换推荐模块 HTML
                    const parser = new DOMParser();
                    const htmlDoc = parser.parseFromString(data.recommend_html, 'text/html');
                    const newBlock = htmlDoc.querySelector('#recommend-container');
                    const oldBlock = document.querySelector('#recommend-container');
                    oldBlock.replaceWith(newBlock);

                    openAlert('更新成功！', 'success');
                } catch (err) {
                    openAlert('推荐更新失败，请稍后再试');
                }
            }
        });

        document.getElementById('clear-input')?.addEventListener('click', ()=>{
            const input = document.getElementById('search');
            if (input) input.value = '';
            document.getElementById('searchBtn').click();
        })

        document.getElementById('clear-search')?.addEventListener('click', () => {
            const input = document.getElementById('search');
            if (input) input.value = '';
            document.getElementById('searchBtn').click();
        });
    </script>
{% endblock %}